/*
 * 版权：Copyright (c) 2019 China
 *
 * 创建日期：Wednesday August 14th 2019
 * 创建者：ymq(ymq) - <<email>>
 *
 * 修改日期: Wednesday, 14th August 2019 12:03:49 pm
 * 修改者: ymq(ymq) - <<email>>
 *
 * 说明
 *  1、账单列表
 */
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import SignFrameLayout, { InputType } from "src/business/components/buss-components/sign-frame-layout";
import { AppServiceUtility } from "src/projects/app/appService";
import { Select, Modal, Form, Radio, Button, Icon, Upload, message } from 'antd';
import { request_func, exprot_excel } from "src/business/util_tool";
import { MainCard } from "src/business/components/style-components/main-card";
import XLSX from 'xlsx';
const { Option } = Select;
/**
 * 组件：账单列表列表视图状态
 */
export interface BillRecodeViewState extends ReactViewState {
    /** 接口名 */
    request_url?: string;
    isAll?: boolean;
    financial_list?: any;
    show?: boolean;
    preview?: boolean;
    preview_parm?: any;
    /** 导出url */
    export_url?: string;
    /** 是否显示上传按钮 */
    upload?: boolean;
    fileList?: any;
    uploading?: boolean;
    file_data?: any;
    data?: any;
}
export interface ServiceItemPackageFormValues {
    id?: string;
}
/**
 * 组件：账单列表列表视图
 * 描述
 */
export class BillRecodeView extends ReactView<BillRecodeViewControl, BillRecodeViewState> {
    private columns_data_source = [{
        title: '账单号',
        dataIndex: 'financial_id',
        key: 'financial_id',
    },
    {
        title: '长者姓名',
        dataIndex: 'user.name',
        key: 'user.name',
    },
    {
        title: '身份证',
        dataIndex: 'user.id_card',
        key: 'user.id_card',
    }, {
        title: '付款方姓名',
        dataIndex: 'pay.extend_info.card_name',
        key: 'pay.extend_info.card_name',
    },
    {
        title: '付款方账号',
        dataIndex: 'pay.extend_info.card_number',
        key: 'pay.extend_info.card_number',
    },
    {
        title: '收款方姓名',
        dataIndex: 'receiver.extend_info.card_name',
        key: 'receiver.extend_info.card_name',
    },
    {
        title: '收款方账号',
        dataIndex: 'receiver.extend_info.card_number',
        key: 'receiver.extend_info.card_number',
    },
    {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
    },
    {
        title: '产生时间',
        dataIndex: 'date',
        key: 'date',
    },
    {
        title: '扣款状态',
        dataIndex: 'pay_status',
        key: 'pay_status',
    }];
    constructor(props: BillRecodeViewControl) {
        super(props);
        this.state = {
            request_url: '',
            export_url: '',
            isAll: false,
            financial_list: [],
            show: false,
            preview: false,
            preview_parm: [],
            upload: false,
            fileList: [],
            uploading: false,
            file_data: '',
            data: {}
        };
    }
    /** 打印按钮 */
    print = () => {
        this.setState({ upload: true });
    }
    /** 导出按钮 */
    export = () => {
        this.setState({ show: true });
    }
    requesr_finacial(financial_id: any, func?: Function) {
        request_func(this, AppServiceUtility.financial_account_service![this.state.request_url!], [financial_id], (data: any) => {
            func && func(data);
        });
    }
    // 预览
    onOk(isOk: boolean) {
        const { form } = this.props;
        form!.validateFields((err: Error, values: ServiceItemPackageFormValues) => {
            const parm = values['isAll'] === 0 ? [values['financial_id']] : [{}];
            if (!values['isAll'] && !values['financial_id']) {
                message.info('暂无数据可预览');
                return;
            }
            this.setState({ preview: true, preview_parm: parm });
        });
    }
    // 下载
    download() {
        const data = this.state.data;
        if (data.result && data.result.length) {
            const key = '账单号';
            const financial_id = [this.state.data.result[0][key]];
            request_func(this, AppServiceUtility.financial_account_service[this.state.export_url!], financial_id, (data: any) => {
                console.log(data.result);
                exprot_excel([{ name: '银行扣款单', value: data.result }], '银行扣款单', 'xls');
                this.setState({ preview: false, data: {}, preview_parm: [] });
            });
        } else {
            message.info('暂无数据可下载');
        }

    }
    // 显示/取消弹窗
    onCancel(data: any) {
        this.setState(data);
    }
    // 导出类型选择
    onChangeRadio(value: any) {
        const isAll = value === 0;
        this.setState({ isAll });
        if (isAll) { // 若选择导出账单号，则要获取账单列表，供下拉选择
            this.requesr_finacial({ pay_status: '待付款' }, (data: any) => {
                if (data.result.length > 0) {
                    let financial_list: any = [];
                    data.result.map!((item: any) => { // 账单号去重
                        if (item.hasOwnProperty('financial_id') && item.financial_id !== '' && !financial_list.includes(item.financial_id)) {
                            financial_list.push(item.financial_id);
                        }
                    });
                    this.setState({ financial_list });
                }
            });
        }
    }
    // 导入
    handleUpload = () => {
        this.setState({
            uploading: true,
            upload: true,
        });
        request_func(this, AppServiceUtility.financial_account_service.upload_excel_manage, [this.state.file_data], (data: any) => {
            message.info(data);
            if (data === '导入成功') {
                location.reload();
            }
        });
        this.setState({ fileList: [], uploading: false, upload: false });
    }
    // 查询成功
    onsucess_func(data: any) {
        if (data.result.length) {
            this.setState({ data });
        }
        console.info('查询成功了');
        console.info(data);
    }
    componentWillMount() {
        this.setState({
            request_url: this.props.request_url,
            export_url: this.props.export_url,
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form!;
        const status = ['成功', '失败', '待付款'];
        let reconciliation_info_list = {
            type_show: false,
            btn_props: [{
                label: '导入',
                btn_method: this.print,
                icon: 'plus'
            }, {
                label: '导出',
                btn_method: this.export,
                icon: 'plus'
            }],
            edit_form_items_props: [
                {
                    type: InputType.input,
                    label: "长者姓名",
                    decorator_id: "user_name"
                },
                {
                    type: InputType.select,
                    label: "支付状态",
                    decorator_id: "pay_status",
                    option: {
                        placeholder: "请选择状态",
                        showSearch: true,
                        childrens: status!.map((item) => <Option key={item} value={item}>{item}</Option>),
                    }
                },
                {
                    type: InputType.input,
                    label: "单号",
                    decorator_id: "financial_id"
                },
                {
                    type: InputType.input,
                    label: "收款账户姓名",
                    decorator_id: "receiver_name"
                }, {
                    type: InputType.rangePicker,
                    label: "产生时间",
                    decorator_id: "date"
                }
            ],
            columns_data_source: this.columns_data_source,
            showHeader: true,
            bordered: false,
            show_footer: true,
            rowKey: 'id',
            service_object: AppServiceUtility.financial_account_service,
            service_option: {
                select: {
                    service_func: this.state.request_url,
                    service_condition: [{}, 1, 10]
                }
            },
            permission_class: this.props.permission_class,
            get_permission_name: this.props.get_permission_name,
            select_permission: this.props.select_permission,
            add_permission: this.props.add_permission,

        };
        // 导出账单预览配置
        let json_list = {
            type_show: false,
            columns_data_source: [{
                title: '账单号',
                dataIndex: '账单号',
                key: '账单号',
            }, {
                title: '付款方姓名',
                dataIndex: '付款方姓名',
                key: '付款方姓名',
            }, {
                title: '付款方账号',
                dataIndex: '付款方账号',
                key: '付款方账号',
            }, {
                title: '收款方姓名',
                dataIndex: '收款方姓名',
                key: '收款方姓名',
            }, {
                title: '收款方账号',
                dataIndex: '收款方账号',
                key: '收款方账号',
            }, {
                title: '金额',
                dataIndex: '金额',
                key: '金额',
            }, {
                title: '状态',
                dataIndex: '状态',
                key: '状态'
            }
            ],
            onsucess_func: (data: any) => { this.onsucess_func(data); },
            service_object: AppServiceUtility.financial_account_service,
            service_option: {
                select: {
                    service_func: this.state.export_url,
                    service_condition: this.state.preview_parm
                }
            },
        };
        // 导入组件配置
        // const { uploading, fileList } = this.state;
        const props = {
            onRemove: (file: any) => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    console.info('newFileList', newFileList);
                    return {
                        fileList: newFileList,
                        uploading: false,
                    };
                });
            },
            beforeUpload: (file: any, fileList: any) => {
                const fileType = file.name.split('.').slice(-1)[0];
                const typeList = ['xls', 'xlsx'];
                console.info('文件格式：：', file.name.split('.'), fileType);
                if (!typeList.includes(fileType)) {
                    message.info('文件格式错误，请导入xls或xlsx格式的文件');
                    return false;
                }
                const _this = this;
                var files = file;
                var fileReader = new FileReader();
                fileReader.onload = function (ev: any) {
                    let file_data: any = [];
                    try {
                        var data = ev!.target.result,
                            workbook = XLSX.read(data, {
                                type: 'binary'
                            }); // 以二进制流方式读取得到整份excel表格对象
                        file_data = []; // 存储获取到的数据
                    } catch (e) {
                        console.log('文件类型不正确');
                        return;
                    }

                    // 表格的表格范围，可用于判断表头是否数量是否正确
                    var fromTo: any = '';
                    // 遍历每张表读取
                    for (var sheet in workbook.Sheets) {
                        if (workbook.Sheets.hasOwnProperty(sheet)) {
                            fromTo = workbook.Sheets[sheet]['!ref'];
                            console.log('文件内容', fromTo);
                            file_data = file_data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                            break; // 如果只取第一张表，就取消注释这行
                        }
                    }

                    _this.setState({ file_data });
                };

                // 以二进制方式打开文件
                fileReader.readAsBinaryString(files);
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList: this.state.fileList,
        };
        return (
            <div>
                <SignFrameLayout {...reconciliation_info_list} />
                <Modal
                    title="请选择导出类型"
                    visible={this.state.show}
                    onOk={() => this.onOk(false)}
                    onCancel={() => this.onCancel({ show: !this.state.show })}
                    okText="预览"
                    cancelText="取消"
                >
                    <MainCard>
                        <Form>
                            <Form.Item>
                                {getFieldDecorator('isAll', {
                                    initialValue: 1
                                })(
                                    <Radio.Group onChange={(e: any) => { this.onChangeRadio(e.target.value); }}>
                                        <Radio key={1} value={1}>全部未导出过的账单号</Radio>
                                        <Radio key={0} value={0}>选择账单号导出</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            {
                                this.state.isAll ? (
                                    <Form.Item>
                                        {getFieldDecorator('financial_id', {
                                            initialValue: this.state.financial_list ? this.state.financial_list[0] : ''
                                        })(
                                            <Select>
                                                {
                                                    this.state.financial_list!.map((provinceItem: any, index: any) => {
                                                        return <Option key={provinceItem}>{provinceItem}</Option>;
                                                    })
                                                }
                                            </Select>
                                        )}
                                    </Form.Item>
                                ) : null
                            }
                        </Form>
                    </MainCard >
                </Modal >
                <Modal
                    title="预览"
                    visible={this.state.preview}
                    onOk={() => this.download()}
                    onCancel={() => this.onCancel({ preview: !this.state.preview })}
                    okText="下载"
                    width={1000}
                    cancelText="取消"
                >
                    {this.state.preview ? <SignFrameLayout {...json_list} /> : null}
                </Modal>
                <Modal
                    title="导入银行回款单"
                    visible={this.state.upload}
                    footer={null}
                    onCancel={() => { this.onCancel({ upload: !this.state.upload }); }}
                >
                    {this.state.upload ? (<div>
                        <Upload {...props}>
                            <Button disabled={this.state.fileList.length === 1}>
                                <Icon type="upload" /> {'选择文件'}
                            </Button>
                        </Upload>
                        <Button
                            type="primary"
                            onClick={this.handleUpload}
                            disabled={this.state.fileList.length === 0}
                            loading={this.state.uploading}
                            style={{ marginTop: 16 }}
                        >
                            {this.state.uploading ? '上传中...' : '上传'}
                        </Button>
                    </div>) : null}
                </Modal></div >
        );
    }
}

/**
 * 控件：账单列表视图控制器
 * 描述
 */
@addon('BillRecodeView', '账单列表视图', '描述')
@reactControl(Form.create<any>()(BillRecodeView), true)
export class BillRecodeViewControl extends ReactViewControl {
    /** 请求接口名 */
    public request_url?: string;
    /** 获取权限接口类 */
    public permission_class?: any;
    /** 获取权限接口方法名 */
    public get_permission_name?: string;
    /** 查询权限 */
    public select_permission?: string;
    /** 新增权限 */
    public add_permission?: string;
    /** 导出权限 */
    public export_url?: string;

}